package com.gta.edu.sdk.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.gta.edu.sdk.common.dto.Page;

public class GsonUtils {
	
	/**
	 * 将对象转为Json字符串
	 * @param obj
	 * @return
	 */
	public static String parseJson(Object obj){
		if(obj == null) return null;
		GsonBuilder builder = new GsonBuilder();
		builder.setDateFormat("yyyy-MM-dd HH:mm:ss");
		Gson gson = builder.create();
		return gson.toJson(obj);
	}
	
	/**
	 * json字符串转对象
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static Object json2Obj(String json , Class<?> clazz){
		if(json == null || "".equals(json.trim())){
			return null;
		}
		GsonBuilder builder = new GsonBuilder();
		builder.setDateFormat("yyyy-MM-dd HH:mm:ss");
		Gson gson = builder.create();
		return gson.fromJson(json, clazz);
	}
	
	/**
	 * 将对象转化成一个新对象
	 * @param src
	 * @param clazz
	 * @return
	 */
	public static Object parseObj(Object src , Class<?> clazz){
		if(src == null) return null;
		String json = parseJson(src);
		return json2Obj(json, clazz);
	}
	
	/**
	 * 转化列表
	 * @param list
	 * @param clazz
	 * @return
	 */
	public static List<?> parseList(List<?> list , Class<?> clazz){
		if(list != null){
			List<Object> newList = new ArrayList<>();
			for (Object object : list) {
				Object obj = parseObj(object , clazz);
				newList.add(obj);
			}
			return newList;
		} else {
			return null;
		}
	}
	
	/**
	 * 转化列表
	 * @param list
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List<?> parseCollection(Collection<?> collection , Class<?> clazz){
		if(collection != null){
			List newList = new ArrayList<>();
			for (Object object : collection) {
				Object obj = parseObj(object , clazz);
				newList.add(obj);
			}
			return newList;
		} else {
			return null;
		}
	}
	
	/**
	 * 转化Page
	 * @param list
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Page<?> parsePage(Page<?> page , Class clazz){
		List list = page.getResult();
		if(list != null){
			List newList = new ArrayList<>();
			for (Object object : list) {
				Object obj = parseObj(object , clazz);
				newList.add(obj);
			}
			page.setResult(newList);
			return page;
		} else {
			return null;
		}
	}
	/**
	 * json转map
	 * @param result
	 * @param key
	 * @param value
	 * @return
	 */
	public static Map<String, Object> JsonToMap(Map<String, Object> result, String key, JsonElement value) {
	    // 如果key为null 直接报错
	    if (key == null) {
	        throw new RuntimeException("key值不能为null");
	    }
	    // 如果value为null,则直接put到map中
	    if (value == null) {
	        result.put(key, value);
	    } else {
	        // 如果value为基本数据类型，则放入到map中
	        if (value.isJsonPrimitive()) {
	            result.put(key, value.getAsString());
	        } else if (value.isJsonObject()) {
	            // 如果value为JsonObject数据类型，则遍历此JSONObject，进行递归调用本方法
	            JsonObject jsonObject = value.getAsJsonObject();
	            Iterator<Entry<String, JsonElement>> iterator = jsonObject.entrySet().iterator();
	            while (iterator.hasNext()) {
	                Entry<String, JsonElement> next = iterator.next();
	                result = JsonToMap(result, next.getKey(), next.getValue());
	            }
	        } else if (value.isJsonArray()) {
	            // 如果value为JsonArray数据类型，则遍历此JsonArray，进行递归调用本方法
	            JsonArray jsonArray = value.getAsJsonArray();
	            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	            for (int i = 0, len = jsonArray.size(); i < len; i++) {
	                Map<String, Object> tempMap = new HashMap<String, Object>();
	                JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
	                Iterator<Entry<String, JsonElement>> iterator = jsonObject.entrySet().iterator();
	                while (iterator.hasNext()) {
	                    Entry<String, JsonElement> next = iterator.next();
	                    tempMap = JsonToMap(tempMap, next.getKey(), next.getValue());
	                }
	                list.add(tempMap);
	            }
	            result.put(key, list);
	        }
	    }
	    // 返回最终结果
	    return result;
	}
	/**
	 * 要转换的json字符串
	 * @param jsonStr
	 * @return
	 */
	public static Map<String, Object> JsonToMap(String jsonStr) {
	    return JsonToMap(jsonStr, null);
	}
	/**
	 * 转换的结果放入位置
	 * @param jsonStr
	 * @param result
	 * @return
	 */
	public static Map<String, Object> JsonToMap(String jsonStr, Map<String, Object> result) {
	    if (jsonStr == null) {
	        return null;
	    }
	    if (result == null) {
	        result = new HashMap<String, Object>();
	    }
	    JsonParser jsonParser = new JsonParser();
	    JsonElement jsonElement = jsonParser.parse(jsonStr);
	    return JsonToMap(result, jsonStr, jsonElement);
	}
	/**
	 * @param map
	 * @return
	 */
	   public static String mapToJson(Map<String, String> map) {  
	        Set<String> keys = map.keySet();  
	        String key = "";  
	        String value = "";  
	        StringBuffer jsonBuffer = new StringBuffer();  
	        jsonBuffer.append("{");  
	        for (Iterator<String> it = keys.iterator(); it.hasNext();) {  
	            key = (String) it.next();  
	            value = map.get(key);  
	            jsonBuffer.append(key + ":" +"\""+ value+"\"");  
	            if (it.hasNext()) {  
	                jsonBuffer.append(",");  
	            }  
	        }  
	        jsonBuffer.append("}");  
	        return jsonBuffer.toString();  
	    }  
}
